
#include "timer1_drv.h"
#if USE_TIMER1

/**
 * @desc  : Gpio初始化
 * @date  : 2025-03-31
 * @author: AnRui
 * @note  :
 */
static void Timer1GPIOInit() {
    rcu_periph_clock_enable(RCU_GPIOA);
    gpio_init(GPIOA, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_10MHZ, GPIO_PIN_0);
}


/**
 * @desc  : timer0初始化
 * @date  : 2025-03-31
 * @author: AnRui
 * @note  : 开启输入捕获功能
 */
void Timer1DrvInit(void) {
    /* 使能定时器时钟；*/
    rcu_periph_clock_enable(RCU_TIMER1);
    /* 复位定时器；*/
    timer_deinit(TIMER1);

    timer_parameter_struct timerInitPara;
    timer_struct_para_init(&timerInitPara);
    /* 设置预分频器值；*/
    timerInitPara.prescaler = TIMER1_PSC - 1;     // 输入给计数器的时钟频率为1Mhz，周期1us
    /* 设置自动重装载值；*/
    timerInitPara.period = TIMER1_PERIOD;
    timer_init(TIMER1, &timerInitPara);

    timer_ic_parameter_struct icInitPara;
    timer_channel_input_struct_para_init(&icInitPara);
		
	  /* PA0 同时捕获上升沿和下降沿 通道捕获不用使能 发现上升沿或下降沿 自动把计数器的值 记录到寄存器中 硬件实现的*/
	  /* 物理引脚 PA0 输入通道0 下降沿捕获*/
    icInitPara.icpolarity = TIMER_IC_POLARITY_RISING;
    icInitPara.icselection = TIMER_IC_SELECTION_DIRECTTI;
    timer_input_capture_config(TIMER1, TIMER_CH_0, &icInitPara);

		/* 物理引脚 PA0 重映射到  输入通道1 上升沿捕获 */
    icInitPara.icpolarity = TIMER_IC_POLARITY_FALLING;
    icInitPara.icselection = TIMER_IC_SELECTION_INDIRECTTI;
    timer_input_capture_config(TIMER1, TIMER_CH_1, &icInitPara);
	
    /* 使能定时器的捕获中断；*/
    timer_interrupt_flag_clear(TIMER1, TIMER_INT_FLAG_CH0);
    timer_interrupt_enable(TIMER1, TIMER_INT_CH0);
    /* 使能定时器中断和优先级；*/
    nvic_irq_enable(TIMER1_IRQn, TIMER1_IRQ_PRIORITY);
    Timer1GPIOInit();
    /* 使能定时器；*/
    timer_enable(TIMER1);
}

static uint32_t g_periodUs;
static uint32_t g_pulseUs;
 
void TIMER1_IRQHandler(void) {
    if (timer_interrupt_flag_get(TIMER1, TIMER_INT_FLAG_CH0) == SET) {
        timer_interrupt_flag_clear(TIMER1, TIMER_INT_FLAG_CH0);
				// 获取捕获寄存器0的值
				g_periodUs = timer_channel_capture_value_register_read(TIMER1, TIMER_CH_0) + 1;
			  // 获取捕获寄存器1的值
				g_pulseUs =  timer_channel_capture_value_register_read(TIMER1, TIMER_CH_1) + 1;
				timer_counter_value_config(TIMER1, 0);
    }
}



void CaptureDrvTest(void) {
    printf("period is %d us, pulse is %d us.\n", g_periodUs, g_pulseUs);
}
#endif 

